package cn.admin.remoting.impl;

import cn.admin.remoting.Connection;
import cn.admin.remoting.RequestProcessor;
import cn.admin.remoting.util.ConnectionUrl;
import cn.admin.remoting.util.DIYExecutor;
import org.apache.mina.common.IdleStatus;

import java.util.concurrent.Executor;

public class HeartBeatProcessor implements RequestProcessor<ConnectionHeartBeat> {

    private static final byte HEARTBEAT_RESPONSE = 1;
    public static final HeartBeatProcessor instance = new HeartBeatProcessor();

    @Override
    public Class<ConnectionHeartBeat> interest() {
        return ConnectionHeartBeat.class;
    }

    @Override
    public void handleRequest(ConnectionHeartBeat request, AppResponseOutput output) {
        String clientUrl = request.getClientUrl();
        if (clientUrl != null) {
            Connection conn = output.getConnection();
            conn.setAttribute("ClientUrl",clientUrl);
            int idleTime = ConnectionUrl.getIdleTimeout(clientUrl);
            if (idleTime > 0) {
                ((DefaultConnection)conn).getIoSession().setIdleTime(IdleStatus.READER_IDLE,idleTime);
            }
        }
        output.write(1);
    }

    @Override
    public Executor getExecutor() {
        return DIYExecutor.getInstance();
    }

    @Override
    public void onRejectedExecutionException(ConnectionHeartBeat appRequest, AppResponseOutput respOut) {
    }

    public static String clientTargetUrl(Connection connection) {

        return connection.isClientSide() ? null : (String)connection.getAttribute("ClientUrl");

    }

}
